
import 'dart:convert';
import 'dart:io';

import 'package:app/qrcode_module/qrcan_result_page.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:get/get_navigation/src/routes/transitions_type.dart';
import 'package:image_picker/image_picker.dart';
import 'package:scan/scan.dart';
import 'dart:async';
// import 'package:images_picker/images_picker.dart';


import '../net/dio_manager.dart';
import '../net/persisten_storage.dart';

class QRCodePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return QRCodePageState();
  }
}

class QRCodePageState extends State<QRCodePage> {
  String _platformVersion = 'Unknown';

  ScanController controller = ScanController();
  String qrcode = 'Unknown';

  final ImagePicker _picker = ImagePicker();


  var _json;

  void requestData(var product_id,var type)async{
    var params = {
      'access_token': await PersistentStorage().getStorage('acctoken'), //#获取access_token 每天不一样目前
      'uid': await PersistentStorage().getStorage('uid'),                                  // #当前用户 uid
      'partner_id': await PersistentStorage().getStorage('partner_id'),                           //#当前用户partner_id
      'model': 'product.product',  //# 当前对象
      'function_name': '_api_dt_open_source_community_buy',  // 返回一条记录
      'product_id': product_id, // # 返回一条记录
      'type': type,  //# 来源
    };
    var result  = await DioManager().kkRequest('/api/v1/public_getattr/0',params:params);

    var json = jsonDecode(result);

    _json = json;
    if(json['errcode']==-1){
      BotToast.showText(text: '${json['message']}');
      return;
    }
    if(json['errcode']==100){

      print('community_websocket_http '
          '= ${await PersistentStorage().getStorage('community_websocket_http')}');
      Get.off(QRCanResultPage('${json['data']['python_version']}',_json));

      String dataStr = jsonEncode(json);
      requestPostSend('${dataStr}');

      // channel!.sink.add(
      //  '${json['data']['app_list']}'
      // );

      return;
    }

    if(json['message']=='转购物车!'){

      var json = '''
      {
            "errcode": 0,
            "errmsg": "ok",
            "data": {
                "python_version": "3.7",
                "python_env": "",
                "app_list": ""
            },
            "message": "已加购物车!"
        }
      ''';

      // String dataStr = jsonEncode(json);

      requestPostSend('${json}');

      // Get.off(ShoppingCartPage());
      // eventBus.fire(EventFn('jumpToShopCard'));
    }else{
      // Get.off(PayOrderPage(json['data'][0]['id'],json['data'][0]['amount_total']));
    }
  }

  ///# 发送 #
  void requestPostSend(var message)async{

    var formData  = FormData.fromMap({
      'message':message,
    });

    try{
      var response = await Dio().
      post('${await PersistentStorage().getStorage('community_websocket_http')}',
          data: formData,options: Options(responseType:ResponseType.plain));
      print('==== post === ${response.data}');
    }catch(e){
      print(e);
    }

    // var result  = await DioManager().rcRequset('/api/v1/public_getattr/0',params:params);

  }

  /// # #手机扫码成功
  void requestWithLogin() async {
    var list = qrcode.split(',');

    var params;
    params = {
      'access_token': await PersistentStorage().getStorage('acctoken'),
      'uid': await PersistentStorage().getStorage('uid'),
      'partner_id': await PersistentStorage().getStorage('partner_id'),
      'model': 'ir.qrcode',
      'function_name': '_api_is_scan', // #用户接口名称
      'uuid': list[1],
      'login': '', // #登陆帐号
    };

    var result  = await DioManager().kkRequest('/api/v1/getattr/0',params:params);

    var json = jsonDecode(result);
    // String result =
    // await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
    //     .post(Address.getattt, data: params);
    // Map json = jsonDecode(result);

    // if (json['errmsg'] == 'ok') {
    //   if (list[0] == 'qr_code_login') {
    //     Get.off(QREnterLoginPage(list[1], json['message']),
    //         transition: Transition.downToUp);
    //   }
    // }
  }


  @override
  void initState() {
    super.initState();
    initPlatformState();

    Map<String, dynamic> headers = new Map();

    headers['origin'] = 'wss://x.xx.com:443/ws/'; // 加上一个origin，防止被拦截



    // channel = IOWebSocketChannel.connect(
    //     'ws://:7060/ws',
    //     // 可以设置请求头
    //     headers: headers
    // );

  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await Scan.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('扫一扫'),
        actions: [
          TextButton(
              onPressed: () async {
                final XFile? image = await _picker.pickImage(source: ImageSource.gallery,imageQuality: 100);
                print(image!.path);
                String? str =  await Scan.parse(image.path);
                if (str != null) {
                  setState(() {
                    qrcode = str;
                    print('相册识别结果===='+str);
                  });
                }

                // List<Media> res = await ImagesPicker.pick();
                // if (res != null) {
                //   String str = await Scan.parse(res[0].path);
                //   if (str != null) {
                //     setState(() {
                //       qrcode = str;
                //     });
                //   }
                // }

              },
              child: Text('相册'))
        ],
      ),
      body: Column(
        children: [
          // Text('Running on: $_platformVersion\n'),
          // Wrap(
          //   children: [
          //     ElevatedButton(
          //       child: Text("toggleTorchMode"),
          //       onPressed: () {
          //         controller.toggleTorchMode();
          //       },
          //     ),
          //     ElevatedButton(
          //       child: Text("pause"),
          //       onPressed: () {
          //         controller.pause();
          //       },
          //     ),
          //     ElevatedButton(
          //       child: Text("resume"),
          //       onPressed: () {
          //         controller.resume();
          //       },
          //     ),
          //     ElevatedButton(
          //       child: Text("parse from image"),
          //       onPressed: () async {
          //         // List<Media> res = await ImagesPicker.pick();
          //         // if (res != null) {
          //         //   String str = await Scan.parse(res[0].path);
          //         //   if (str != null) {
          //         //     setState(() {
          //         //       qrcode = str;
          //         //     });
          //         //   }
          //         // }
          //       },
          //     ),
          //   ],
          // ),
          Expanded(
              child: Stack(
                children: [
                  Container(
                    width: Get.width,
                    child: ScanView(
                      controller: controller,
                      scanAreaScale: .7,
                      scanLineColor: Colors.blue.shade300,
                      onCapture: (data) {
                        setState(() {
                          qrcode = data;
                          print('result===== ${qrcode}');

                          bool isHaveType = qrcode.contains('type');

                          if(isHaveType==true){
                            List s = qrcode.split('=');
                            print('===== ${s}');
                            String code = s[1];
                            var code1 = code.split('&');
                            print('===== ${code1[0]} ${s[3]}');
                            Future.delayed(Duration(milliseconds: 250), () {
                              requestData(s[3], code1[0]);
                            });
                          }else if(qrcode.contains('qr_code_login')==true){
                            requestWithLogin();
                          }else if(qrcode.contains('product')==true){
                            var list = qrcode.split(',');
                            requestData(list[1], '_api_dt_open_source_community_buy_ok');
                          }
                          else{
                            Get.off(QRCanResultPage(qrcode,_json));
                          }

                        });
                      },
                    ),
                  ),
                  Container(child: Align(
                    alignment: Alignment.bottomCenter,
                    child: TextButton(
                      child: Text('打开闪光灯',style: TextStyle(color: Colors.white),),
                      onPressed: (){
                        controller.toggleTorchMode();
                      },
                    ),
                  ),)
                ],
              ))
          // Text('scan result is $qrcode'),
        ],
      ),
    );
  }
}
